package com.tenglong.teacher.ui.homepage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.cuotibao.zhuoxiao.basics.utils.glide.GlideOptions;
import com.cuotibao.zhuoxiao.basics.utils.recyview.DividerSpaceItemDecoration;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.ClassInfoBean;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.SeClass;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.HomePagerAdapter;
import com.tenglong.teacher.ui.port.MainFragmentRubsh;
import com.tenglong.teacher.ui.common.activity.BaseActivity;
import com.tenglong.teacher.ui.common.view.CircleImageView;
import com.tenglong.teacher.ui.common.view.SlideDialog;
import com.tenglong.teacher.ui.setting.UserDetailsActivity;


import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/12/23 0023.
 */

public class FragmentHompage extends Fragment implements MainFragmentRubsh, TabLayout.OnTabSelectedListener,
        SlideDialog.SlideDialogListener, OnRefreshListener, HomePagerAdapter.HomePagerListener, View.OnClickListener {
    public final String KEY_HOME_PAPER_POSITION = "key_home_paper_position";
    private List<ClassInfoBean> seClasses;
    private TabLayout mTab;
    private TextView mTeacherName;
    private TextView mSlogan;
    private CircleImageView mHeaderImage;
    /**
     * 此fragment是否加载过
     */
    private boolean isLoadFragment = false;
    /**
     * 一对一和我的班级所以 type
     */
    public static final String TYPE_ONE_AND_CLASS = "0";
    /**
     * 一对一type
     */
    public static final String TYPE_ONE_TO_ONE = "2";
    /**
     * 我的班课type
     */
    public static final String TYPE_ALL_CLASS = "1";

    /**
     * 当前所属type
     */
    private String currentType = TYPE_ALL_CLASS;

    /**
     * 点击item的位置
     */
    private int mClickPosition = -1;

    private Context mContext;
    private View noClass;
    private TextView createClass;
    private SlideDialog mSlideDialog;
    private RefreshLayout mSmartRefreshLayout;

    private boolean isFirstRequestData = true;
    private RecyclerView mRecyclerView;
    private HomePagerAdapter mAdapter;
    private FrameLayout parentView;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.containsKey(KEY_HOME_PAPER_POSITION)) {
            currentType = savedInstanceState.getString(KEY_HOME_PAPER_POSITION);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getContext()).inflate(R.layout.fragment_homepage, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initRecy();
        setHeaderInfo();
        setAdapter();
        setListeners();
        mTab.post(new Runnable() {
            @Override
            public void run() {
                TabLayout.Tab tab = mTab.getTabAt(currentType.equals(TYPE_ALL_CLASS) ? 0 : 1);
                if (tab != null) {
                    tab.select();
                }
            }
        });
        if (currentType.equals(TYPE_ALL_CLASS)) {
            getClassInfo(currentType);
        }
    }


    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_HOME_PAPER_POSITION, currentType);
    }

    private void initRecy() {
        mRecyclerView.addItemDecoration(new DividerSpaceItemDecoration(Utils.dip2px(mContext, 10)));
        mRecyclerView.setHasFixedSize(true);
    }

    private void setAdapter() {
        seClasses = new ArrayList<>();
        mAdapter = new HomePagerAdapter(seClasses);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setListeners() {
        mAdapter.setHomePagerListener(this);
        mTab.addOnTabSelectedListener(this);
        ((View) mHeaderImage.getParent()).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(mContext, UserDetailsActivity.class), GlobalConstant.REQUEST_CODE_USER_DETAIL);
            }
        });
        createClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSlideDialog.showAsDropDown(createClass);
            }
        });
        mSlideDialog.setSlideDialogListener(this);
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
        noClass.setOnClickListener(this);
    }

    private void initView(View view) {
        ((TextView) view.findViewById(R.id.action_text)).setText("首页");
        view.findViewById(R.id.action_button1).setVisibility(View.GONE);
        mTeacherName = view.findViewById(R.id.tv_name);
        mSlogan = view.findViewById(R.id.tv_slogan);
        mHeaderImage = view.findViewById(R.id.iv_header);
        mTab = view.findViewById(R.id.tablayout);
        mTab.addTab(mTab.newTab().setText("我的班课"));
        mTab.addTab(mTab.newTab().setText("我的一对一"));
        noClass = view.findViewById(R.id.noClass);

        parentView = view.findViewById(R.id.fl);

        createClass = view.findViewById(R.id.complete);

        mRecyclerView = view.findViewById(R.id.mRecyclerView);

        mSmartRefreshLayout = view.findViewById(R.id.mSmartRefreshLayout);
        ClassicsHeader headerView = new ClassicsHeader(mContext);
        ClassicsFooter footView = new ClassicsFooter(mContext);
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        mSmartRefreshLayout.setRefreshHeader(headerView);
        mSmartRefreshLayout.setRefreshFooter(footView);

        createClass.setVisibility(View.VISIBLE);
        createClass.setText("+创建班级");
        mSlideDialog = new SlideDialog(mContext);
        isLoadFragment = true;
    }

    private void setHeaderInfo() {
        ClientUserInfo userInfo = DataState.getInstance().getUserInfo();
        mSlogan.setVisibility(TextUtils.isEmpty(userInfo.getSlogan()) ? View.GONE : View.VISIBLE);
        if (mSlogan.getVisibility() == View.VISIBLE) {
            mSlogan.setText(StringUtil.replaceBlank(userInfo.getSlogan()));
        }
        mTeacherName.setVisibility(TextUtils.isEmpty(userInfo.getUserName()) ? View.GONE : View.VISIBLE);
        if (mTeacherName.getVisibility() == View.VISIBLE) {
            mTeacherName.setText(StringUtil.replaceBlank(userInfo.getUserName()));
        }
        RequestOptions options = GlideOptions.getGlideRequestOptions().
                error(R.drawable.setting_image_defauft_header).
                placeholder(R.drawable.header_image_loading);
        Glide.with(this)
                .load(IpUtils.getImageUrl(userInfo.getPhotoUrl()))
                .apply(options)
                .into(mHeaderImage);
    }

    private void getClassInfo(final String type) {
        if (isFirstRequestData) {
            ((BaseActivity) mContext).showProgressDialog("数据加载中...");
            isFirstRequestData = false;
        }
        CreateRequestEntity.getWebService().getAllClassByUserId(type).enqueue(new Callback<BaseResult<List<SeClass>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<SeClass>>> call, Response<BaseResult<List<SeClass>>> response) {
                ((BaseActivity) mContext).dismissProgressDialog();
                mSmartRefreshLayout.finishRefresh(true);
                if (ResultVerifier.isSucceed(response)) {
                    seClasses.clear();
                    seClasses.addAll(response.body().data);
                    mAdapter.notifyDataSetChanged();
                    currentType = type;
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                parentView.bringChildToFront(seClasses.size() == 0 ? noClass : mRecyclerView);
                noClass.setVisibility(seClasses.size() == 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onFailure(Call<BaseResult<List<SeClass>>> call, Throwable t) {
                ((BaseActivity) mContext).dismissProgressDialog();
                mSmartRefreshLayout.finishRefresh(false);
                ResultVerifier.systerErrers(t);
                parentView.bringChildToFront(seClasses.size() == 0 ? noClass : mRecyclerView);
                noClass.setVisibility(seClasses.size() == 0 ? View.VISIBLE : View.GONE);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_USER_DETAIL:
                    setHeaderInfo();
                    break;
                case GlobalConstant.REQUEST_CODE_STUDENT_SIGN_ACTIVITY:
                    if (data != null && seClasses != null && mAdapter != null && seClasses.size() > mClickPosition && mClickPosition != -1) {
                        SeClass info = (SeClass) seClasses.get(mClickPosition);
                        info.setInClass(data.getBooleanExtra(GlobalConstant.RESULT_CODE_STUDENT_SIGN_ACTIVITY, false));
                        mAdapter.notifyItemChanged(mClickPosition);
                    }
                    mClickPosition = -1;
                    break;
                case GlobalConstant.REQUEST_CODE_CREATE_CLASS_ACTIVITY:
                    if (data != null) {
                        int type = data.getIntExtra(CreateClassActivity.KEY_RETURN_CLASS_TYPE, CreateClassActivity.CREATE_CLASS);
                        if ((type == CreateClassActivity.CREATE_CLASS && currentType.equals(TYPE_ALL_CLASS))
                                || (type == CreateClassActivity.ONE_TO_ONE && currentType.equals(TYPE_ONE_TO_ONE))) {
                            getClassInfo(currentType);
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
            case 1:
                getClassInfo(TYPE_ONE_TO_ONE);
                break;
            case 0:
                getClassInfo(TYPE_ALL_CLASS);
                break;
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void refresh() {
        if (isAdded() && isLoadFragment) {
            setHeaderInfo();
            getClassInfo(currentType);
        }
    }

    @Override
    public void onSlideDialogListener(String text) {
        Intent intent = new Intent();
        intent.putExtra(CreateClassActivity.KEY_CREATE_CLASS_TYEP, text.equals("建班课") ? CreateClassActivity.CREATE_CLASS : CreateClassActivity.ONE_TO_ONE);
        intent.setClass(mContext, CreateClassActivity.class);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_CREATE_CLASS_ACTIVITY);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getClassInfo(currentType);
    }

    @Override
    public void onHomePagerListener(int position) {
        if (position == -1) return;
        this.mClickPosition = position;
        Intent intent = new Intent();
        intent.setClass(mContext, StudentSignActivity.class);
        intent.putExtra(StudentSignActivity.KEY_DAYA, (SeClass)seClasses.get(position));
        intent.putExtra(StudentSignActivity.KEY_CURRENT_TYPE, currentType);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_STUDENT_SIGN_ACTIVITY);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.noClass:
                Intent intent = new Intent();
                intent.putExtra(CreateClassActivity.KEY_CREATE_CLASS_TYEP, currentType.equals(TYPE_ALL_CLASS) ? CreateClassActivity.CREATE_CLASS : CreateClassActivity.ONE_TO_ONE);
                intent.setClass(mContext, CreateClassActivity.class);
                startActivityForResult(intent, GlobalConstant.REQUEST_CODE_CREATE_CLASS_ACTIVITY);
                break;
        }
    }
}
